package vn.gq.app4vn.doctruyen;

import org.json.JSONObject;

import vn.gq.cd.model.bean.AdmobItem;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.NetworkOption;
import android.app.Activity;
import android.util.Log;

public class AdmobAdLoader {
	
	private String apiUrl;
	private UngDungVietApp application;
	private Activity mActivity;
	
	public AdmobAdLoader(Activity activity) {
		mActivity = activity;
		apiUrl = String.format("http://apps.cucdinh.vn/ads/admob?id=%s&t=text", activity.getPackageName());
		application = (UngDungVietApp) activity.getApplication();
	}
	
	public void load() {
		load(null);
	}
	
	public void load(final AdLoaderListener listener) {
		if (!application.admAdLoaded) {
			Client client = new Client(mActivity.getApplicationContext());
			client.setCacheTime(3600000); // cache in 1 hour
			client.setNetworkOption(NetworkOption.OPTION_USE_CACHE);
			client.setOutputDataType(DataType.JSON);
			client.executeAndListener(apiUrl, new IClientListener() {
				
				@Override
				public void onDone(int code, Object result) {
					if (BuildConfig.DEBUG) {
						Log.e(getClass().getSimpleName(), String.valueOf(result));
					}
					AdmobItem admobItem = null;
					if (result != null) {
						try {
							admobItem = new AdmobItem((JSONObject) result);
							admobItem.setLoaded(true);
							admobItem.setPreference(mActivity.getApplicationContext());
							application.admAdLoaded = true;
						} catch(Exception e) {
							e.printStackTrace();
						}
					}
					if (listener != null) {
						listener.onDone();
					}
				}
			});
		}
	}
	
	public interface AdLoaderListener {
		void onDone();
	}
}
